use percent_encoding::{percent_encode, NON_ALPHANUMERIC};
use thumbor::protocol::{filter, resize, ImageSpec, Spec};
use thumbor::route::crate_router;

#[tokio::main]
async fn main() {
    // 初始化 tracing
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        .init();
    tracing::info!("日志系统已初始化");

    let app = crate_router();
    tracing::info!("路由已创建");

    let port = std::env::var("PORT").unwrap_or("3000".to_string());
    let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", &port)).await.unwrap();
    tracing::info!("监听地址为:{:?}:{}",listener.local_addr().ok().unwrap().ip(),listener.local_addr().ok().unwrap().port());
    print_test_url("https://images.pexels.com/photos/1562477/pexels-photo-1562477.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260");
    tracing::info!("服务器已启动");

    axum::serve(listener, app.into_make_service()).await.unwrap();
}


// 调试辅助函数
fn print_test_url(url: &str) {
    use std::borrow::Borrow;
    let spec1 = Spec::new_resize(500, 800, resize::SampleFilter::CatmullRom);
    let spec2 = Spec::new_watermark(20, 20);
    let spec3 = Spec::new_filter(filter::Filter::Marine);
    let image_spec = ImageSpec::new(vec![spec1, spec2, spec3]);
    let s: String = image_spec.borrow().into();
    let test_image = percent_encode(url.as_bytes(), NON_ALPHANUMERIC).to_string();
    println!("test url: http://localhost:3000/image/{}/{}", s, test_image);
}
